﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Windows.Forms;

namespace WChat {
    /// <summary>
    /// 访问http服务器类
    /// </summary>
    public  class BaseService
    {
        public static CookieContainer CookiesContainer;

        #region 发送Get请求

        public byte[] SendGetRequest(string url) {
            try {
                 GC.Collect();
                HttpWebRequest request=null;
                if (request != null) {
                    request.Abort();
                }
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";
                request.KeepAlive = false;
                if (CookiesContainer == null)   //如果没有cookie容器，则创建一个
                 {
                    CookiesContainer = new CookieContainer();
                 }
               // request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
                request.CookieContainer = CookiesContainer;  //启用cookie
                //MessageBox.Show("可能会超时的地方");
                string cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri); //把cookies转换成字符串
              // MessageBox.Show("发送wozijipost请求：" + cookiesstr);
                request.Timeout=3000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();
                int count = (int)response.ContentLength;
                ////MessageBox.Show(count.ToString());
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                response.Close();
                return buf;
            }
            catch(Exception e) {
              //  MessageBox.Show(e.ToString());
                return null;
            }
            return null;
        }
        #endregion

        #region 发送post请求
        /// <summary>
        /// 向服务器发送post请求 返回服务器回复数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public byte[] SendPostRequest(string url, string body) {
            try {
                byte[] request_body = Encoding.UTF8.GetBytes(body);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.ContentLength = request_body.Length;
                //request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
                //request.Accept = "*/*";
                //request.KeepAlive = true;
                //request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                //request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2");
                Stream request_stream = request.GetRequestStream();

                request_stream.Write(request_body, 0, request_body.Length);
                // CookieContainer CookiesContainer;
                if (CookiesContainer == null) {
                    CookiesContainer = new CookieContainer();
                }
                request.CookieContainer = CookiesContainer;  //启用cookie
                string cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri); //把cookies转换成字符串
             //   MessageBox.Show("发送post请求：" + cookiesstr);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return buf;
            }
            catch {
                return null;
            }
        }
        #endregion

        #region 自己的方法
        /// <summary>
        /// 自己设置cookies的get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] GetMyFriendsRequest(string url, string user) {
            try {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";
                request.Headers.Add("Cookie", CookieDictionary.GetCookies(user));
               // MessageBox.Show("获取我的好友信息" + CookieDictionary.GetCookies(user));
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return buf;
            }
            catch {
                return null;
            }
        }

        public byte[] GetRequestFromFile( string url, string file ) {
            try {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";
                request.Headers.Add("Cookie",file);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();
                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return buf;
            }
            catch {
                return null;
            }
        }

        /// <summary>
        /// 通过发送post请求来获取cookies
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetCookies(string url, string body) {
            try {
                byte[] request_body = Encoding.UTF8.GetBytes(body);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.ContentLength = request_body.Length;

                Stream request_stream = request.GetRequestStream();

                request_stream.Write(request_body, 0, request_body.Length);
                if (CookiesContainer == null) {
                    CookiesContainer = new CookieContainer();
                }
                 request.CookieContainer = CookiesContainer;  //启用cookie
                string cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri); //把cookies转换成字符串
               //MessageBox.Show("发送wozijipost请求：" + cookiesstr);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return cookiesstr;
            }
            catch {
                return null;
            }
        }

        /// <summary>
        /// 我自己写的post方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns> 
        public byte[] MyPostRequest(string url, string body, string user) {
            try {
                byte[] request_body = Encoding.UTF8.GetBytes(body);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.ContentLength = request_body.Length;
                Stream request_stream = request.GetRequestStream();
                request_stream.Write(request_body, 0, request_body.Length);
                // MessageBox.Show("发送post请求,这是我自己的方法：" + CookieDictionary.GetCookies(user));
                request.Headers.Add("Cookie", CookieDictionary.GetCookies(user));
                request.Timeout = 2000;  //设置超时时间
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
              //  MessageBox.Show(count.ToString());
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return buf;
            }
            catch (Exception e){
                WriteLog.Writelog("MyPostRequest", e.ToString());
                return null;
            }
        }
        #endregion

        public void WriteCookie(CookieContainer C ) {
            StringBuilder sbc = new StringBuilder();
            List<Cookie> cooklist = GetAllCookies(C);
            foreach (Cookie cookie in cooklist) {
             //   sbc.AppendFormat("{0};{1};{2};{3};{4};{5}\r\n", cookie.Domain,cookie.Name,cookie.Path,cookie.Port,cookie.Secure.ToString(), cookie.Value);
                sbc.Append(cookie);
            }
            string path = "D:\\chinarencookies.txt";
            FileStream fs = File.Create(path);
            fs.Close();
            File.WriteAllText(path, sbc.ToString(), System.Text.Encoding.Default);
            MessageBox.Show(sbc.ToString());
          }

        /// <summary>
        /// 获取指定cookies
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public Cookie GetCookie(string name) {
            List<Cookie> cookies = GetAllCookies(CookiesContainer);
            foreach (Cookie c in cookies) {
                if (c.Name == name) {
                    return c;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取所有的cookie
        /// </summary>
        /// <param name="cc"></param>
        /// <returns ></returns>
        private List<Cookie> GetAllCookies(CookieContainer cc) {
            List<Cookie> lstCookies = new List<Cookie>();   //创建一个cookie类型的数组

            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values) {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });

                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies)
                        lstCookies.Add(c);
            }
            return lstCookies;
        }

        
    }
}
